#include "component.h"
#include "luaWrapper.h"

#include <QDebug>

Component::Component()
  : cells(0),
    fuelCost(0),
    price(0)
{
}

ComponentMap Component::getComponents(const std::string &filename)
{
  return getComponents(QStringList(filename.c_str()));
}

ComponentMap Component::getComponents(const QStringList &files)
{
  ComponentMap ret;

  LuaWrapper lua;
  foreach (QString f, files)
  {
    lua.load(f);
  }

  lua_getglobal(lua.mLua, "components");
  if (lua_istable(lua.mLua, -1))
  {
    lua_pushnil(lua.mLua);
    while(lua_next(lua.mLua, -2) != 0)
    {
      if (lua_isstring(lua.mLua, -2))
      {
        Component c;
        c.name = lua_tostring(lua.mLua, -2);
        if (!lua.getTableField(-1, "cells", c.cells))
        {
          qDebug() << "Could not find cells of type int for " << c.name;
        }
        if (!lua.getTableField(-1, "fuelCost", c.fuelCost))
        {
          qDebug() << "Could not find fuelCost of type double for " << c.name;
        }
        if (!lua.getTableField(-1, "price", c.price))
        {
          qDebug() << "Could not find price of type int for " << c.name;
        }
        if (!lua.getTableField(-1, "description", c.description))
        {
          qDebug() << "Could not find description of type string for " << c.name;
        }
        ret[c.name] = c;
      }
      lua_pop(lua.mLua, 1);
    }
    lua_pop(lua.mLua, 1); //components table
  }
  else
  {
    lua.warning("cannot find components table");
  }

  return ret;
}
